#!/usr/bin/python
# -*- coding: utf-8 -*-

#This file is part of pyLot library.
#
# pyLot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyLot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pyLot.  If not, see <http://www.gnu.org/licenses/>.

__author__ = u'Pierre Puiseux, Guillaume Baty'
__copyright__ = u"Copyright 2011-2012 (C) andheo, Université de Pau et des Pays de l'Adour"
__credits__ = [u'Pierre Puiseux', u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"

import sys

from _pylot.interfaces.handler import HandlerInterface
from _pylot.minimal.utils import check_type
from _pylot.minimal.path import Path
from _pylot.minimal.config import ConfigOptionContainer
from _pylot.minimal.pathbook import PathBook
from _pylot.defaultconf import hardbook
from _pylot.minimal.system import ENCODING

class MainHandler (HandlerInterface):

  def __init__(self, plugin_path=None, plugin_id=None):
    HandlerInterface.__init__(self, plugin_path, plugin_id)
    self.widget_scheme = u'tabs'
    self.history = ConfigOptionContainer()
    history_file = self.findFile(u'main_handler.csv')
    self.history.importfile(history_file, fmt=u'csv')

  def runScript (self, script, args=[], wait=True):
    check_type(u'script', script, [unicode, Path])
    if Path(script).isfile() :
      self.history[u'scriptpaths'] = script
      if args :
        self.history[u'scriptparams'] = u','.join(args)
      oldstate = self.process.wait
      self.process.wait = wait

      pathbook = PathBook()
      pathbook.upgrade(hardbook)
      pathbook[u'script'] = Path(script)

      pythonpath = pathbook(u'script').parent.encode(ENCODING)
      if pythonpath not in sys.path :
        sys.path.append(pythonpath)

      global_vars = {}

      global_vars.update(self._children)
      for child in self._children.values() :
        global_vars.update(child.script_globals)
        pathbook.upgrade(child.script_pathbook)

      global_vars.update({
      u'main_manager': self,
      u'pathbook': pathbook,
      u'process': self.process,
      u'raw_input':self.io.rawInput,
      u'wait':wait,
      u'args':args,
      u'write':self.io.write
      })

      try :
        # execfile cannot support unicode :-(
        execfile(script.encode(ENCODING), global_vars)

        try :
          required = global_vars['REQUIRED']
        except :
          required = []

        FAILED = False
        for req in required :
          if req not in self._children :
            self.io.writeStderr(tr_(u'Script requires plugin %s\n') % req ,
            u'warn')
            FAILED = True
            break
        if not FAILED :
          global_vars['main']()

      except SystemExit :
        self.io.writeStderr(tr_(u'Script fails with return code %s\n') % sys.exc_value,
          u'warn')
        self.process.wait = oldstate
      # finally :
      #   self.process.wait = oldstate
      self.process.wait = oldstate

  def _readSettings(self, settings, common):
    settings.beginGroup(u'UserInterface')
    level = settings.getValue(u"level", self.level).value
    self.widget_scheme = settings.getValue(u"widget_scheme", self.widget_scheme).value
    if level != self.level :
      self.switchUserLevel(level)
    settings.endGroup()
    settings.beginGroup(u'Scripts')
    book = settings.getContainer(default_book=self.history)
    self.history.userUpgrade(book)
    settings.endGroup()

  def _writeSettings(self, settings, common):
    settings.beginGroup(u'UserInterface')
    settings.setValue(u"level", self.level)
    settings.setValue(u"widget_scheme", self.widget_scheme)
    settings.endGroup()
    settings.beginGroup(u'Scripts')
    settings.setContainer(self.history)
    settings.endGroup()
